<template>
	<view>
		<u-navbar :title="navTitle" :autoBack="true" :placeholder="true">
			<view class="u-nav-slot" slot="right">
				<!-- <u-icon name="more-dot-fill"></u-icon> -->
			</view>
		</u-navbar>
		<view class="chat-container">
			<scroll-view style="background-color: #f5f5f5;" class="chat-window messages" scroll-y="true"
				show-scrollbar="true" :scroll-with-animation="true" :scroll-top="scrollTop"
				:style="{height: style.contentViewHeight + 'px'}">
				<!-- <view class="messages" ref="chatContainer"> -->
				<view v-for="(item, index) in messages" :key="index" :class="item.role" class="cu-chat">
					<!-- Assistant Messages (state 0) -->
					<view class="messages-item" v-if="item.state==0">
						<img :src="avatar_url" alt="" srcset="" class="avatar_url" />
						<view class="messageList" style="margin-right: 10px;">
							<MdRenderVue :md_view="item.renderedMarkdown" v-if="item.renderedMarkdown" />
							<u-loading-icon v-else></u-loading-icon>
							<view v-if="item.extLinks" style="color: #999;padding-bottom: 10px">
								数据来源：{{item.extLinks.name}}</view>
						</view>
					</view>
					<!-- User Messages (state 1) -->
					<view class="messages-item" v-if="item.state==1" style="justify-content: flex-end;">
						<view class="messageList" style="margin-right: 10px;margin-left: 10px;">
							<MdRenderVue :md_view="item.renderedMarkdown" v-if="item.renderedMarkdown" />
							<u-loading-icon v-else></u-loading-icon>
							<view v-if="item.extLinks" style="color: #999;padding-bottom: 10px">
								数据来源：{{item.extLinks.name}}</view>
						</view>
						<img :src="item.userinfo.avatar_url" alt="" srcset="" class="avatar_url" />
					</view>
				</view>
				<!-- </view> -->
			</scroll-view>
			<view class="input-area">
				<u-textarea v-model="content" placeholder="请输入您的问题" @confirm="sendMessage" @keyup.enter="sendMessage"
					autoHeight border="bottom" />
				<!-- <view @click="sendMessage" class="sendMessage">发送</view> -->
				<u-loading-icon v-if="loadingState"></u-loading-icon>
				<img src="../../static/images/ico_01.png" alt="" srcset="" @click="sendMessage" v-else />

			</view>
		</view>
	</view>
</template>

<script>
	import dayjs from "dayjs"
	import {
		marked
	} from 'marked'
	import MdRenderVue from "../../components/MdRender.vue";
	import {
		PostChatCreateApi
	} from '@/api/main.js'
	export default {
		data() {
			return {
				navTitle: "校园知识库", // nav 标题
				content: '', //用户输入的内容
				messages: [{
					conversationId:"",
					state: "0", // 0表示左边(助手)，1表示右边(用户)
					userinfo: {
						avatar_url: ""
					},
					renderedMarkdown: 'Hi, how can I help you today?'
				}, ],
				conversationId: "",
				datasetId: "",
				scrollTop: 0,
				access_token: "",
				avatar_url: "",
				style: {
					contentViewHeight: 0,
					mitemHeight: 0
				},
				scrollTop: 0,
				loadingState: false,
			};
		},
		onLoad(options) {
			console.log(options)
			uni.setNavigationBarTitle({
				title: options.title
			})
			this.navTitle = options.title
			this.conversationId = options.conversationId
			this.datasetId = options.datasetId
			this.access_token = options.access_token
			this.avatar_url = options.avatar_url
			const res = uni.getSystemInfoSync(); //获取手机可使用窗口高度 
			this.style.contentViewHeight = res.windowHeight - 115;
			// res.windowHeight:屏幕的高度减去,输入框的高度及导航栏的高度,得到信息的需要展示的高度
		},
		components: {
			MdRenderVue
		},
		methods: {
			scrollToBottom() {
				let query = uni.createSelectorQuery();
				query.selectAll('.cu-chat').boundingClientRect();
				query.selectAll('.cu-chat').boundingClientRect();

				query.exec((res) => {
					this.style.mitemHeight = 0;
					res[0].forEach((rect) => {
						// console.log('rect.height', parseInt(rect.height))
						this.style.mitemHeight = parseInt(this.style.mitemHeight) + parseInt(rect.height )
					})
					console.log('this.style.mitemHeight', parseInt(this.style.mitemHeight))
					//获取所有内部子元素的高度,遍历得到总高度

					/** 因为vue的虚拟DOM 每次生成的新消息都是之前的，所以采用异步setTimeout   
					 * 主要就是添加了这定时器
					 */
					if (this.style.mitemHeight > (this.style.contentViewHeight)) {
						// console.log(this.style.mitemHeight - this.style.contentViewHeight)
						//判断子元素高度是否大于显示高度
						this.scrollTop = parseInt(this.style.mitemHeight)+135
						//用子元素的高度减去显示的高度就获益获得序言滚动的高度
					}
				})
			},
			async sendMessage() {
				if (this.content == '') {
					uni.showToast({
						title: '请输入您的问题',
						icon: "none"
					})
					return
				} else {
					// 将用户消息推送到messages数组
					this.messages.push({
						conversationId:this.conversationId,
						state: "1", //右边用户消息
						userinfo: {
							avatar_url: uni.getStorageSync("userInfo").avatar ? uni.getStorageSync("userInfo")
								.avatar : '../../static/images/ico_02.png'
						},
						renderedMarkdown: this.content
					}, );
					this.scrollToBottom()
					// 将用户输入通过API发送到服务器
					this.loadingState = true
					const response = await PostChatCreateApi({
						"conversationId": this.conversationId,
						"role": "user",
						"content": this.content,
						"time": dayjs().format("YYYY-MM-DD HH:mm:ss"),
						"datasetId": this.datasetId,
						"extDetails": {
							"table": {
								"dsName": "master",
								"tableNames": [
									"ai_bill"
								]
							}
						}
					})
					

					this.loadingState = false
					// 创建一个 EventSource 对象以监听事件流
					const access_token = this.access_token;
					const TENANT_ID = 1;
					const key = response.data;
					const eventSource = new EventSource(
						`http://oai.huat.edu.cn:6302/admin/chat/msg/list?access_token=${access_token}&TENANT-ID=${TENANT_ID}&key=${key}`
					);
					// const eventSource = new EventSource(
					// 	`http://10.20.73.136:6302/admin/chat/msg/list?access_token=${access_token}&TENANT-ID=${TENANT_ID}&key=${key}`
					// );
					const eventData = {
						state: "0", //0 左侧助手消息
						conversationId:this.conversationId,
						userinfo: {
							avatar_url: ""
						},
						renderedMarkdown: "", //初始化为空，稍后填充
						extLinks: null,
					}
					this.messages.push(eventData);
					this.content = ""
					eventSource.addEventListener('message', event => {
						const data = JSON.parse(event.data);
						if (data.message != "[DONE]") {
							let eventMessage = data.message;
							eventMessage = eventMessage.replace(/^['"]|['"]$/g, '') //去除多余的单引号
							const markdowntext = `${eventData.renderedMarkdown}${eventMessage}`
							eventData.renderedMarkdown = markdowntext
							this.messages[this.messages.length - 1].renderedMarkdown = markdowntext
							this.messages[this.messages.length - 1].extLinks = data.extLinks[0]
							this.scrollToBottom()
						}

					});
					eventSource.addEventListener('error', event => {
						eventSource.close();
					});
				}
				uni.setStorageSync("messages",this.messages)
			},

		}
	};
</script>

<style lang="scss" scoped>
	.chat-container {
		height: calc(100vh - 115px);
	}

	.chat-list {
		height: calc(100vh - 115px);
		padding: 10px;
		overflow-y: auto;
	}

	.messages {
		.messages-item {
			display: flex;
			overflow: auto;
			padding: 10px;

			.avatar_url {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
			}

			.messageList {
				display: flex;
				flex-wrap: wrap;
				padding: 5px 10px;
				border-radius: .625rem;
				box-shadow: 2px 2px 3px rgba(0, 0, 0, .1), 0 0 3px rgba(0, 0, 0, .1);
				word-break: break-word;
				background-color: rgba(255, 255, 255, 0.25);
			}
		}

		.messages .user {
			text-align: right;
		}

		.messages .assistant {
			text-align: left;
		}
	}

	.input-area {
		height: 50px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		border-top: 1px solid #f2f2f2;

		.sendMessage {
			color: #4f46e5;
			padding: 5px 10px;
			border-radius: 5px;
		}

		img {
			width: 35px;
			height: 35px;
		}
	}
</style>